package org.wjw;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;

@WebServlet("/showRequest")
public class ShowServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //定义一个StringBuilder
        StringBuilder stringBuilder = new StringBuilder();
        //获取方法名
        String method = req.getMethod();
        stringBuilder.append(method);
        stringBuilder.append("<br>");

        //获取URL
        String URL = req.getRequestURI();
        stringBuilder.append(URL);
        stringBuilder.append("<br>");
        //获取协议
        String protocol = req.getProtocol();
        stringBuilder.append(protocol);
        stringBuilder.append("<br>");
        //获取ContextPath
        String contextPath = req.getContextPath();
        stringBuilder.append(contextPath);
        stringBuilder.append("<br>");
        //获取QueryString
        String queryString = req.getQueryString();
        stringBuilder.append(queryString);
        stringBuilder.append("<br>");
        System.out.println("query string : " + queryString);

        //获取Header
        // 获取的是一个枚举类型
        Enumeration<String> headerNames = req.getHeaderNames();
        // 遍历这个枚举
        while (headerNames.hasMoreElements()) {
            //获取每一个key
            String headerKey = headerNames.nextElement();
            //通过headerKey来获取Value
            String headerValue = req.getHeader(headerKey);
            // 加入返回结果的字符串
            stringBuilder.append(headerKey).append(": ").append(headerValue);
            stringBuilder.append("<br>");
        }
        // 设置响应的ContentType为HTML
        resp.setContentType("text/html;charset = utf-8");

        //返回响应
        resp.getWriter().write(stringBuilder.toString());

    }
}
